﻿using System;
using System.Collections.Generic;
using System.Linq;
using CloudShot.Core.Interfaces;
using CloudShot.Settings;

namespace CloudShot.Logic
{
  internal class StorageContainer
  {
    private readonly IConfigurationSection _appConfiguration;

    private IImageStorage _activeStorage;
    public event Action<IImageStorage> ActiveStorageChanged;

    public IImageStorage ActiveStorage
    {
      get { return _activeStorage; }
      set
      {
        if (_activeStorage == value)
          return;

        _activeStorage = value;

        var settings = _appConfiguration.GetOrCreateAs<CloudShotSettings>();
        settings.ActiveStorageName = _activeStorage != null ? _activeStorage.Name : string.Empty;
        _appConfiguration.SaveAs(settings);

        InvokeStorageChanged(_activeStorage);
      }
    }
    
    public IEnumerable<IImageStorage> Storages { get; private set; }

    public StorageContainer(IEnumerable<IImageStorage> storages, IConfigurationSection appConfiguration)
    {
      _appConfiguration = appConfiguration;
      var settings = _appConfiguration.GetOrCreateAs<CloudShotSettings>();

      Storages = storages.ToList();

      _activeStorage = Storages.FirstOrDefault(s => s.Name == settings.ActiveStorageName) ?? Storages.FirstOrDefault(); //first by name, or just first storage
    }

    private void InvokeStorageChanged(IImageStorage storage)
    {
      Action<IImageStorage> handler = ActiveStorageChanged;
      if (handler != null)
        handler(storage);
    }
  }
}